package other.xsy.pms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.exception.*;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.pms.utils.ComUtils;
import other.xsy.pms.utils.HCXObjectService;
import other.xsy.pms.utils.PromotionApiUtil;
import other.xsy.pms.utils.TfReturnMsgTools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：同步客户到pms系统
 *
 * @author 黄梓豪 and whz
 * @ClassName: AccountToPmsTrigger
 * @Description:
 * @date 2024年03月15日
 */
@RestApi(baseUrl = "/account")
public class AccountToPmsTrigger implements Trigger {

    private static final Logger logger = LoggerFactory.getLogger();
    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static String LOG_MSG_EX = "同步客户到pms系统 ";
    private static Long KA_ENTITY_TYPE = -11010000100001L; // KA客户

    public static void main(String[] args) throws ApiEntityServiceException {
        Account account = new Account();
        account.setId(3225088825429333L);
        account = hcxObjectService.get(account);
        AccountToPmsTrigger test = new AccountToPmsTrigger();
        test.handler(account);
    }

    @RestMapping(value = "/pushPms", method = RequestMethod.POST)
    public String pushPms(@RestQueryParam(name = "id") Long id) throws ApiEntityServiceException {
        logger.info(LOG_MSG_EX + "执行了按钮事件：" + id);
        Account account = new Account();
        account.setId(id);
        account = hcxObjectService.get(account);
        boolean result = handler(account);
        if (result) {
            return TfReturnMsgTools.getSuccessResult("推送成功");
        }
        return TfReturnMsgTools.getFailResult("推送失败");
    }

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Account> accountList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Account account = (Account) xObject;
            accountList.add(account);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        handler(accountList.get(0));
        return new TriggerResponse(true, "", dataResultList);
    }

    public boolean handler(Account account) {
        try {
            logger.info("客户名称：" + account.getAccountName());
            //业务代码
            sendToPms(account);
            account.setSyncStatus__c(2);
            return true;
        }catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
            account.setSyncStatus__c(3);
            return false;
        }finally {
            try {
                // 更新同步次数字段
                long count = 1L;
                if (account.getSyncCount__c() != null) {
                    count += account.getSyncCount__c();
                }
                account.setSyncCount__c(count);
                hcxObjectService.update(account);
            } catch (ApiEntityServiceException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendToPms(Account account) throws IOException, CustomConfigException, XsyHttpException, CacheException {
        //获取报文
        JSONArray requestMsg = buidlMsg(account);
        logger.info("请求报文为" + requestMsg.toJSONString());
        //发送请求
        JSONObject jsonObject = PromotionApiUtil.sendToPms(requestMsg, PromotionApiUtil.getAccountUrl());
        logger.info("返回结果为" + jsonObject);
    }

    private JSONArray buidlMsg(Account account) throws IOException {
        JSONArray profession__c = ComUtils.getGlobalPicks("profession__c");//行业通用选项集
        JSONArray subsectors__c = ComUtils.getGlobalPicks("subsectors__c");//子行业通用选项集
        JSONArray jsonArray = new JSONArray(); // 创建 JSONArray 对象
        //构建json
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("customerId", account.getAccountNo__c()); // 客户编码  必填
        jsonObject.put("customerName", account.getAccountName()); // 客户名称
        jsonObject.put("industry", ComUtils.getOptionLabel(profession__c, account.getProfession__c())); // 行业
        jsonObject.put("subdividedIndustry", ComUtils.getOptionLabel(subsectors__c, account.getSubsectors__c())); // 子行业
        jsonObject.put("reserved1", KA_ENTITY_TYPE.equals(account.getEntityType()) ? "1" : "0");  //是否KA客户
        jsonArray.add(jsonObject);
        return jsonArray;
    }
}
